package com.qf.lanzhou.blog.api.controller;

import com.alibaba.fastjson.JSON;
import com.qf.lanzhou.blog.api.pojo.vo.BaseRespVO;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

/**
 * doPost带参数请求，封装成的父类
 * 使用带参数请求后台统一继承此类
 */
public class BaseServletPost extends HttpServlet{
    /**
     * 接收前端传入的信息
     * @param req
     * @param clazz 业务信息的反射对象
     * @param <T> 业务信息类型
     * @return 业务信息
     */
    public <T>T paramsToEntity(HttpServletRequest req,Class<T> clazz){
        //创建输入流读取前端带的json
        //通过StringBuffer拼接
        StringBuffer json = new StringBuffer();
        BufferedReader reader = null;
        try {
            reader = req.getReader();
            String str;
            //将输入流的内容读入data数组，再进行拼接
            while ((str = reader.readLine()) != null){
                json.append(str);
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        T object = JSON.parseObject(json.toString(), clazz);
        return object;
    }

    /**
     * 将标准结果返回给前端
     * @param resp
     * @param result 封装好的标准
     */
    protected void writerResult(HttpServletResponse resp, BaseRespVO result){
        String jsonString = JSON.toJSONString(result);
        try {
            resp.getWriter().write(jsonString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将成功的标准信息封装成json返回
     * @param data 成功只需将业务信息进行返回
     * @param resp
     */
    protected void successResultWrite(Object data,HttpServletResponse resp){
        BaseRespVO<Object> result = new BaseRespVO<>();
        result.setData(data);
        writerResult(resp,result);
    }

    /**
     * 将失败的信息封装成json返回
     * @param msg 失败需要传送错误信息，改变状态码
     * @param resp
     */
    protected  void failedResultWrite(String msg,HttpServletResponse resp){
        BaseRespVO<Object> result = new BaseRespVO<>();
        result.setMsg(msg);
        result.setCode(BaseRespVO.CodeType.FAILED.getValue());
        writerResult(resp,result);
    }

}
